﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using ETModel;
using UnityEditor;

namespace ETEditor
{
	internal class OpcodeInfo
	{
		public string Name;
		public int Opcode;
	}

    public class Proto2CSEditor: EditorWindow
	{
        private const string PacketCodePath = "Assets/GameMain/Scripts/Runtime/Network/Packet";
        private const string ProtobufPacketCodePath = "Assets/GameMain/Scripts/Runtime/Network/Packet/ProtobufPacket";
        private const string CSharpCodeTemplateFileName = "Assets/GameMain/Configs/DataTableCodeTemplate.txt";

        [MenuItem("Tools/Proto2CS")]
        public static void AllProto2CS()
        {
#if UNITY_EDITOR_WIN
            string protoc = protoc = "protoc.exe";
#elif UNITY_EDITOR_OSX
            string protoc = protoc = "protoc";
#endif
            DirectoryInfo theFolder = new DirectoryInfo(@"../Proto/");
            protoc = Path.Combine(theFolder.FullName, protoc);
            FileInfo[] fileInfo = theFolder.GetFiles();
            foreach (FileInfo NextFile in fileInfo)  //遍历文件
            {
                if (NextFile.Extension.Equals(".proto"))
                {
                    //Proto2CS(NextFile.FullName);
                    Process process = ProcessHelper.Run(protoc, "\"./" + NextFile.Name + "\" --csharp_out=\"../Unity/Assets/Hotfix/Game/Message/\"", "../Proto/", true);
                    UnityEngine.Debug.Log(process.StandardOutput.ReadToEnd());
                }
            }
            AssetDatabase.Refresh();
        }
        private static readonly char[] splitChars = { ' ', '\t' };
        public static void Proto2CS(string protoName)
        {
            string s = File.ReadAllText(protoName);

            StringBuilder sb = new StringBuilder();
            sb.Append("using GameMain.Runtime;\n");

            bool isMsgStart = false;

            foreach (string line in s.Split('\n'))
            {
                string newline = line.Trim();

                if (newline == "")
                {
                    continue;
                }

                if (newline.StartsWith("//"))
                {
                    sb.Append($"{newline}\n");
                }

                if (newline.StartsWith("package"))
                {
                    sb.Append("namespace ");
                    sb.Append(newline.Substring(7, newline.Length - 8));
                    sb.Append("\n");
                    sb.Append("{\n");
                }

                if (newline.StartsWith("message"))
                {
                    string parentClass = "";
                    string attributeClass = "";
                    isMsgStart = true;
                    string msgName = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries)[1];
                    string[] ss = newline.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
                    string[] sss = ss[1].Trim().Split(new[] { "_" }, StringSplitOptions.RemoveEmptyEntries);

                    if (ss.Length == 2)
                    {
                        if (msgName.StartsWith("CS"))
                        {
                            parentClass = "CSPacketBase";
                            attributeClass = "CSPacket";
                        }
                        else if (msgName.StartsWith("SC"))
                        {
                            parentClass = "SCPacketBase";
                            attributeClass = "SCPacket";
                        }
                    }

                    sb.Append($"\t[{attributeClass}({sss[0]},{sss[1]})]\n");
                    sb.Append($"\tpublic partial class {msgName} ");
                    if (parentClass != "")
                    {
                        sb.Append($": {parentClass} ");
                    }

                    sb.Append("{}\n\n");
                }

                if (isMsgStart && newline == "}")
                {
                    isMsgStart = false;
                }
            }

            sb.Append("}\n");

            File.WriteAllText(Path.Combine("./Assets/GameMain/Scripts/Runtime/Network/Packet/", Path.GetFileNameWithoutExtension(protoName) + ".Extensions.cs"), sb.ToString());
        }
    }
}
